package com.haoxuer.discover.user.data.dao.impl;

import com.haoxuer.discover.user.oauth.api.OauthHandler;
import com.haoxuer.discover.data.core.CriteriaDaoImpl;
import com.haoxuer.discover.data.core.Finder;
import com.haoxuer.discover.user.data.dao.UserOauthConfigDao;
import com.haoxuer.discover.user.data.entity.UserOauthConfig;

import java.util.HashMap;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2017年07月20日17:47:47.
 */
@Repository

public class UserOauthConfigDaoImpl extends CriteriaDaoImpl<UserOauthConfig, Long> implements UserOauthConfigDao {
  
  private static HashMap<String, OauthHandler> handers = new HashMap<String, OauthHandler>();
  
  @Override
  public UserOauthConfig findById(Long id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }
  
  @Override
  public UserOauthConfig save(UserOauthConfig bean) {
    
    getSession().save(bean);
    
    
    return bean;
  }
  
  @Override
  public UserOauthConfig deleteById(Long id) {
    UserOauthConfig entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }
  
  @Override
  public OauthHandler id(String model) {
    OauthHandler result = null;
    result = handers.get(model);
    if (result == null) {
      Finder finder = Finder.create();
      finder.append("from UserOauthConfig u where u.model=:model");
      finder.setParam("model", model);
      UserOauthConfig config = findOne(finder);
      if (config == null) {
        return null;
      }
      try {
        Class c = Class.forName(config.getClassName());
        result = (OauthHandler) c.newInstance();
        result.setKey(config.getAppKey());
        result.setSecret(config.getAppSecret());
        handers.put(model, result);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InstantiationException e) {
        e.printStackTrace();
      }
    }
    return result;
  }
  
  @Override
  public void clear() {
    if (handers != null) {
      handers.clear();
    } else {
      handers = new HashMap<String, OauthHandler>();
    }
  }
  
  @Override
  protected Class<UserOauthConfig> getEntityClass() {
    return UserOauthConfig.class;
  }
  
  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}